package com.baiwei.vpnapi.service.impl;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.baiwei.vpnapi.dao.DeviceTokenMapper;
import com.baiwei.vpnapi.dao.VpnMessageMapper;
import com.baiwei.vpnapi.entity.IosDeviceToken;
import com.baiwei.vpnapi.entity.VpnMessage;
import com.baiwei.vpnapi.service.PushService;
import com.baiwei.vpnapi.utils.AppUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.notnoop.exceptions.NetworkIOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: vpnapi
 * @description: 推送服务实现
 * @author: Mr. Stone
 * @create: 2020-03-09 15:53
 **/

@Service
public class PushServiceImpl implements PushService {

    @Value("${jiguangpush.appkey}")
    private String jgAppKey;

    @Value("${jiguangpush.mastersecret}")
    private String jgMasterKey;

    @Autowired
    private DeviceTokenMapper deviceTokenMapper;

    @Autowired
    private VpnMessageMapper vpnMessageMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${ios-aps.name}")
    private String apsName;

    // 总推送接口 不分平台，全量推送
    public String pushNofity(String title, String content, Map extra){
        iosPushNotify(title, content, extra);
        String androidRes = androidPushNotify(title, content, extra);
        System.out.println("安卓推送结果: " + androidRes);
        stringRedisTemplate.opsForValue().set("adminToken", AppUtils.generateAuthCode());
        return "推送成功";
    }
    // 苹果推送
    public String iosPushNotify(String title, String content, Map extra) {
        InputStream stream = null;
        try {
            stream = AppServiceImpl.class.getClassLoader().getResource(apsName).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ApnsService service = APNS.newService()
                .withCert(stream, "123456")
                //.withProductionDestination()
                .withSandboxDestination()
                .build();
        String payload = APNS.newPayload()
                .alertTitle(title)
                .customFields(extra)
                .alertBody(content)
                .badge(1)
                .build();
         List<IosDeviceToken> tokens = deviceTokenMapper.selectList(new QueryWrapper<>());
        ArrayList<String> deviceIds = new ArrayList<>();
         for(IosDeviceToken token: tokens) {
             String tokenIdentify = token.getTokenIdentify();
             if(tokenIdentify != null && tokenIdentify.length() > 0) {
                 deviceIds.add(tokenIdentify);
             }
         }
        System.out.println("deviceIds: "+deviceIds);
         try {
             service.push(deviceIds, payload);
         } catch (NetworkIOException e){
             System.out.println("苹果推送错误：" + e.getMessage());
             e.printStackTrace();
         }
        return "推送成功";
    }
    // 安卓推送
    public String androidPushNotify(String title, String content, Map extra){

        JPushClient client = new JPushClient(jgMasterKey, jgAppKey, null, ClientConfig.getInstance());
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(Notification.android(content, title, extra))
                .build();
        try {
            client.sendPush(payload);
        } catch (APIConnectionException e1) {
            return "推送失败:" + e1.getMessage();
        } catch (APIRequestException e2) {
            return "推送失败:" + e2.getMessage();
        }
        return "推送成功";
    }
    //按照消息id推送
    public String pushById(Integer messageId) {
        VpnMessage message = vpnMessageMapper.selectById(messageId);
        if(message == null) {
            throw new RuntimeException("message not exist");
        }
        Map<String, Object> extra = new HashMap<>();
        extra.put("messageId", messageId.toString());
        extra.put("actionType",message.getActionFlag());
        extra.put("param",message.getActionFlag().equals("0")?messageId.toString():message.getLinkUrl());
        return pushNofity(message.getTitle(), message.getContent(), extra);
    }

    //通过id获取推送信息
    public Object messageById(Integer messageId) {
        VpnMessage message = vpnMessageMapper.selectById(messageId);
        if(message == null) {
            throw new RuntimeException("message not exist");
        }
        return message;
    }
}
